package gl.view;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class TabIndictor implements OnCheckedChangeListener,
		OnPageChangeListener {
	private ViewPager mViewPager;
	private RadioGroup mRadioGroup;
	private Context context;
	private View cursor;
	private int screenW;
	private int lastPositon;
	/**
	 * 一个viewpager 滑动状态 指示器 
	 * @param context
	 * @param mViewPager
	 * @param mRadioGroup
	 * @param cursor 指示器图标,会改变view的大小,所以使用ImageView可以保持自定义形状
	 */
	public TabIndictor(Context context, ViewPager mViewPager,
			RadioGroup mRadioGroup, View cursor) {
		this.context = context;
		this.mViewPager = mViewPager;
		mViewPager.setOnPageChangeListener(this);
		this.mRadioGroup = mRadioGroup;
		mRadioGroup.setOnCheckedChangeListener(this);
		this.cursor = cursor;
		InitImageView();
	}

	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		mViewPager.setCurrentItem(getIndexInRadioGroup(group,checkedId));
	}

	public static int getIndexInRadioGroup(RadioGroup group, int checkedId) {
		int index = 0;
		for (int i = 0; i < group.getChildCount(); i++) {
			if (checkedId == group.getChildAt(i).getId()) {
				index = i;
			}
		}
		return index;
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {

	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {

	}

	/**
	 * 初始化动画
	 */
	private void InitImageView() {
		DisplayMetrics dm = new DisplayMetrics();
		((WindowManager) context.getSystemService(Context.WINDOW_SERVICE))
				.getDefaultDisplay().getMetrics(dm);
		screenW = dm.widthPixels;// 获取分辨率宽度
		LayoutParams mLayoutParams = cursor.getLayoutParams();
		mLayoutParams.width = (screenW / mViewPager.getAdapter().getCount());
		cursor.setLayoutParams(mLayoutParams);// 设置动画初始位置
	}

	@Override
	public void onPageSelected(int arg0) {
		((RadioButton) mRadioGroup.getChildAt(arg0)).setChecked(true);

		Animation animation = null;
		animation = new TranslateAnimation(lastPositon
				* (screenW / mViewPager.getAdapter().getCount()), arg0
				* (screenW / mViewPager.getAdapter().getCount()), 0, 0);
		lastPositon = arg0;
		animation.setFillAfter(true);
		animation.setDuration(300);
		cursor.startAnimation(animation);
	}
}
